package com.kefu.boss.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.boss.mapper.BossUserMapper;
import com.kefu.boss.model.BossRole;
import com.kefu.boss.model.BossUser;
import com.kefu.boss.model.BossUserRole;
import com.kefu.boss.vo.BossUserInsertVo;
import com.kefu.boss.vo.BossUserUpdateVo;
import com.kefu.boss.vo.BossUserVo;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.Assert;
import com.kefu.common.util.JacksonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BossUserService extends AbstractKefuService<BossUser>{
    @Resource
    protected BossUserMapper bossUserMapper;
    @Resource
    protected BossUserRoleService bossUserRoleService;

    public BossUser addUser(BossUserInsertVo bossUserVo) {
        // 判断邮箱是否存在
        Assert.isTrue(bossUserMapper.selectCount(Wrappers.lambdaQuery(BossUser.class)
                .eq(BossUser::getUserEmail, bossUserVo.getUserEmail())) > 0, "邮箱["+ bossUserVo.getUserEmail()+"]已经存在!");
        BossUser info = bossUserVo.convert();
        save(info);
        // 添加角色
        if (bossUserVo.getRoleIds() != null && bossUserVo.getRoleIds().length > 0) {
            String userId = info.getUserId();
            List<BossUserRole> list = bossUserVo.roleConvert(userId);
            bossUserRoleService.batchAdd(list);
        }
        logger.info("添加boss用户: {}, {}", bossUserVo, JacksonUtil.toString(info));
        return info;
    }

    public BossUser updateUser(BossUserUpdateVo bossUserVo) {
        BossUser info = bossUserVo.convert();
        updateById(info);
        // 批量修改用户对应的角色（先删除，后新增）
        if (bossUserVo.getRoleIds() != null && bossUserVo.getRoleIds().length > 0) {
            String userId = info.getUserId();
            bossUserRoleService.deleteByUserId(info.getUserId());
            List<BossUserRole> list = bossUserVo.roleConvert(userId);
            bossUserRoleService.batchAdd(list);
        }
        logger.info("编辑boss用户 : {}, {}", bossUserVo, JacksonUtil.toString(info));
        return info;
    }

    public void fillRoleList(List<BossUserVo> records) {
        for (BossUserVo item : records) {
            // 查询用户角色
            List<BossRole> roleList = bossUserRoleService.getRoleList(item.getUserId());
            // 查询createUser的user_name
            if (item.getCreateUser() != null) {
                item.setCreateUserName(getById(item.getCreateUser()).getUserName());
            }
            item.setRoleList(roleList);
        }
    }
}